package com.pallass.security.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.pallass.admin.domain.SysResource;
import com.pallass.admin.domain.SysUser;
import com.pallass.admin.service.SysResourceService;
import com.pallass.admin.service.SysUserService;
import com.pallass.security.CustomerUser;

@Service("userDetailsService")
public class CustomerUserDetailsService implements UserDetailsService {

	private static Logger logger = LoggerFactory.getLogger(CustomerUserDetailsService.class);

	@Autowired
	private SysUserService userService;

	@Autowired
	SysResourceService resourceService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		SysUser u = userService.uniqueUserByUserName(username);
		if (u == null) {
			throw new UsernameNotFoundException("User " + username + " is not found.");
		} else {
			List<GrantedAuthority> authorities = new ArrayList<>();

			List<SysResource> sr = obtainResources(u.getId());

			List<String> permissions = obtainPermissions(u.getId());

			if (permissions != null && !permissions.isEmpty()) {
				logger.debug("{} has permissions: {}.", u.getUserName(), Arrays.toString(permissions.toArray()));

				for (String perm : permissions) {
					if (perm != null && perm.length() > 0) {
						authorities.add(new SimpleGrantedAuthority(perm));
					}
				}
			} else {
				logger.debug("{} has none of permissions.", u.getUserName());
			}

			return new CustomerUser(u.getId(), u.getUserName(), u.getPassword(), authorities, sr);
		}

	}

	public List<SysResource> obtainResourceList() {
		return resourceService.findAll();
	}

	public List<String> obtainPermissions(Integer userId) {
		return resourceService.findPermissionsByUserId(userId);
	}

	public List<SysResource> obtainResources(Integer userId) {
		List<SysResource> resourceList = resourceService.obtainResources(userId);
		List<SysResource> result = new ArrayList<>();
		// 构造父子树
		// SysResource root = new SysResource();
		// root.setId(0);
		// root.setResourceName("根资源");
		// root.setOpen(true);

		for (SysResource sr : resourceList) {
			if (sr.getParent() == null) {
				result.add(sr);
			} else {
				sr.getParent().getChildren().add(sr);
				sr.setParent(null);
			}
		}
		return result;

	}

}
